package com.software.loginregister.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.software.loginregister.R;
import com.software.loginregister.entity.Step;

import java.util.List;

public class StepAdapter extends RecyclerView.Adapter<StepAdapter.StepViewHolder> {
    private List<Step> steps;
    private Context context;

    public StepAdapter(Context context, List<Step> steps) {
        this.context = context;
        this.steps = steps;
    }

    @NonNull
    @Override
    public StepViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.layout_recipe_step_item, parent, false);
        return new StepViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull StepViewHolder holder, int position) {
        Step step = steps.get(position);  // 使用steps而不是stepsList

        // 设置步骤号
        holder.tvStepNumber.setText(String.format("步骤 %d", step.getStepNumber()));
        // 设置描述
        holder.tvStepDescription.setText(step.getDescription());  // 修改为tvStepDescription

        // 根据类型加载图片
        if (step.isUrl()) {
            // 使用Glide加载网络图片
            Glide.with(context)  // 使用成员变量context
                    .load(step.getPhotoUrl())
                    .placeholder(R.drawable.ic_food)
                    .error(R.drawable.ic_food)
                    .centerCrop()
                    .into(holder.ivStepImage);  // 修改为ivStepImage
        } else {
            // 加载本地资源
            holder.ivStepImage.setImageResource(step.getPhotoRes());  // 修改为ivStepImage
        }
    }

    @Override
    public int getItemCount() {
        return steps != null ? steps.size() : 0;
    }

    /**
     * 更新数据
     */
    public void updateData(List<Step> newSteps) {
        this.steps = newSteps;
        notifyDataSetChanged();
    }

    static class StepViewHolder extends RecyclerView.ViewHolder {
        TextView tvStepNumber;
        TextView tvStepDescription;  // 保持与layout中ID一致
        ImageView ivStepImage;      // 保持与layout中ID一致

        public StepViewHolder(@NonNull View itemView) {
            super(itemView);
            tvStepNumber = itemView.findViewById(R.id.tv_step_number);
            tvStepDescription = itemView.findViewById(R.id.tv_step_description);
            ivStepImage = itemView.findViewById(R.id.iv_step_image);
        }
    }
}